<template>
  <div>
    <ul class="message-container">
      <li v-for="(chatRoom, index) in chatRooms" :key="chatRoom.chatSessionID" class="message-item">
        <a class="user-avatar">
          <img class="avatar-item" :src="chatRoom.otherUserAvatar || defaultAvatar" />
        </a>
        <div class="main">
          <div class="info">
            <div class="user-info">
              <a class>{{ chatRoom.otherUserName }}</a>
              <div class="interaction-hint"><span>{{ formatDate(chatRoom.creationTime) }}</span></div>
            </div>

            <div class="interaction-content" @click="toChat(chatRoom.chatSessionID, chatRoom.otherUserID)">
              <span class="message-preview">{{ chatRoom.lastMessage || '暂无消息' }}</span>
              <div v-if="false" class="msg-count">{{ chatRoom.unreadCount }}</div>
            </div>
          </div>
        </div>
      </li>
      <div v-if="chatRooms.length === 0" class="empty-message">
        <el-empty description="暂无聊天记录" />
      </div>
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useRouter } from "vue-router";
import { UserProfileApi } from '@/api/new/userProfleApi.js';
import UserUtil from '@/utils/User/User.js';
import { ElMessage } from 'element-plus';

const router = useRouter();
const chatRooms = ref([]);
const loading = ref(false);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 获取聊天室列表
const fetchChatRooms = async () => {
  if (!UserUtil.isLogin()) {
    ElMessage.warning('请先登录');
    return;
  }
  
  try {
    loading.value = true;
    const userID = UserUtil.getUserId();
    const chatRoomsData = await UserProfileApi.getChatRooms(userID);
    
    // 检查返回的数据是否需要 JSON 解析
    let processedChatRoomsData;
    if (typeof chatRoomsData === 'string') {
      try {
        processedChatRoomsData = JSON.parse(chatRoomsData);
      } catch (e) {
        console.error('解析聊天室数据失败:', e);
        processedChatRoomsData = [];
      }
    } else {
      processedChatRoomsData = chatRoomsData;
    }
    
    // 处理每个聊天室，获取对方用户信息和最后一条消息
    const processedChatRooms = await Promise.all(processedChatRoomsData.map(async (room) => {
      // 确定对方用户ID
      const otherUserID = room.user1ID == userID ? room.user2ID : room.user1ID;
      
      // 获取对方用户信息
      let otherUserInfo = {};
      try {
        otherUserInfo = await UserProfileApi.getUserInfo(otherUserID);
        // 检查返回的用户信息是否需要 JSON 解析
        if (typeof otherUserInfo === 'string') {
          try {
            otherUserInfo = JSON.parse(otherUserInfo);
          } catch (e) {
            console.error(`解析用户 ${otherUserID} 信息失败:`, e);
            otherUserInfo = {};
          }
        }
      } catch (error) {
        console.error(`获取用户 ${otherUserID} 信息失败:`, error);
      }
      
      // 获取最后一条消息
      let lastMessage = '';
      let unreadCount = 0;
      try {
        // 获取聊天室的第一条消息作为预览
        const firstMessageData = await UserProfileApi.getFirstMessage(room.chatSessionID);
        // 检查返回的消息数据是否需要 JSON 解析
        let processedMessageData;
        if (typeof firstMessageData === 'string') {
          try {
            processedMessageData = JSON.parse(firstMessageData);
          } catch (e) {
            console.error(`解析消息数据失败:`, e);
            processedMessageData = null;
          }
        } else {
          processedMessageData = firstMessageData;
        }
        
        // 正确获取消息内容
        if (processedMessageData && processedMessageData.status === 'success' && processedMessageData.firstMessage) {
          lastMessage = processedMessageData.firstMessage.content;
        }
        
        // 获取未读消息数量
        // 这里假设有获取未读消息数量的API，如果没有可以省略
        // const unreadData = await UserProfileApi.getUnreadCount(room.chatSessionID, userID);
        // unreadCount = unreadData.count;
        unreadCount = Math.floor(Math.random() * 10); // 模拟未读消息数量
      } catch (error) {
        console.error(`获取聊天室 ${room.chatSessionID} 消息失败:`, error);
      }
      
      return {
        ...room,
        otherUserID,
        otherUserName: otherUserInfo.username || '未知用户',
        otherUserAvatar: otherUserInfo.headshot || defaultAvatar,
        lastMessage,
        unreadCount
      };
    }));
    
    // 按最后消息时间排序
    chatRooms.value = processedChatRooms.sort((a, b) => 
      new Date(b.creationTime) - new Date(a.creationTime)
    );
  } catch (error) {
    console.error('获取聊天室列表失败:', error);
    ElMessage.error(`获取聊天室列表失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 跳转到聊天页面
const toChat = (chatSessionID, otherUserID) => {
  router.push({ 
    path: "/chat", 
    query: { 
      chatSessionID,
      otherUserID
    } 
  });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;
  
  // 今天内的消息显示时间
  if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
    return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }
  
  // 昨天的消息
  if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
    return `昨天 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }
  
  // 一周内的消息显示星期几
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return `${weekdays[date.getDay()]} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }
  
  // 更早的消息显示完整日期
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

onMounted(() => {
  fetchChatRooms();
});
</script>

<style lang="less" scoped>
.message-container {
  width: 80%;
  .message-item {
    display: flex;
    flex-direction: row;
    padding-top: 24px;

    .user-avatar {
      margin-right: 24px;
      flex-shrink: 0;

      .avatar-item {
        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border-radius: 100%;
        border: 1px solid rgba(0, 0, 0, 0.08);
        object-fit: cover;
      }
    }

    .main {
      flex-grow: 1;
      flex-shrink: 1;
      display: flex;
      flex-direction: row;
      padding-bottom: 12px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
      min-width: 0;

      .info {
        flex-grow: 1;
        flex-shrink: 1;
        min-width: 0;

        .user-info {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 8px;
          a {
            color: #333;
            font-size: 16px;
            font-weight: 600;
          }
          .interaction-hint {
            font-size: 12px;
            color: rgba(51, 51, 51, 0.6);
          }
        }

        .interaction-content {
          display: flex;
          font-size: 14px;
          color: #333;
          line-height: 140%;
          cursor: pointer;
          justify-content: space-between;
          align-items: center;
          min-width: 0;
          
          .message-preview {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
            min-width: 0;
          }
          
          .msg-count {
            width: 20px;
            height: 20px;
            line-height: 20px;
            font-size: 13px;
            color: #fff;
            background-color: red;
            text-align: center;
            border-radius: 100%;
            flex-shrink: 0;
            margin-left: 8px;
          }
        }
      }
    }
  }
}
</style>
